'''
Descripttion: 
version: 
Author: Born
Date: 2020-10-30 22:20:58
LastEditors: Born
'''
from django.shortcuts import render
from django.http import HttpResponse
from django.http.response import HttpResponseRedirect
import requests
from lxml import etree
from django.shortcuts import render, redirect
import re
from django.shortcuts import render
from django.template.loader import get_template
import requests
import json
from django.contrib import auth
from django.contrib.auth.middleware import RemoteUserMiddleware
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.conf import settings
from django.template.loader import get_template


# Create your views here.
def casLogin(request):
    token = request.GET.get('token')
    host = settings.CAS_HOST
    checkUrl = host + "/ssoapi/v2/checkToken"
    getUserInfoUrl = host + "/oauth/getUserInfo"
    appid = settings.CAS_APPID
    appsecret = settings.CAS_APP_SECRET
    # appid = "dataCenter"
    userip = "10.60.10.134"
    headers = {
        "Connection": "close"
    }
    # 判断token
    if(token is None):
        return HttpResponseRedirect(host + '/home/Oauth/getToken/appid/' + appid + '/state/admin.html')
    else:
        if 'HTTP_X_FORWARDED_FOR' in request.META: 
            ip = request.META.get('HTTP_X_FORWARDED_FOR') 
        else:
            ip = request.META.get('REMOTE_ADDR')
        # 兑票
        data = {"token":token,"appid":appid,"appsecret":appsecret,"userip":ip}
        checkData = json.loads(requests.post(checkUrl, headers = headers, data=data).text)
        # 兑票成功
        if(checkData.get("error") == 0):
            data = {"access_token": checkData.get('access_token'),"openid": checkData.get("openid")}
            getUserInfoData = json.loads(requests.post(getUserInfoUrl, headers=headers, data=data).text)
            userCount = User.objects.filter(username=getUserInfoData.get("username")).count()
            if(userCount != 0):
                user = User.objects.get(username=getUserInfoData.get("username"))
                if(user.is_staff!=1 and user.is_active!=1):
                    logout(request)
                    context = {
                        'error': '非管理员无法进入后台',
                        'url': host + '/logout?callback=' + host + '/home/Oauth/getToken/appid/' + appid + '/state/admin.html',
                    }
                    return render(request, 'CasLogin/404.html', context)
            else:
                logout(request)
                context = {
                    'error': '非管理员无法登陆',
                    'url': host + '/logout?callback=' + host + '/home/Oauth/getToken/appid/' + appid + '/state/admin.html',
                }
                return render(request, 'CasLogin/404.html', context)
            # if(user.count()!=0):
            login(request,user)
            if(user.is_staff==1):
                return HttpResponseRedirect('/admin/')
            elif(user.is_active==1):
                return HttpResponseRedirect("/caslogin/loginSuccess")


        # 兑票失败
        else:
            # 请求退出接口
            logout(request)
            context = {
                'error': '登录过期，请重新登录',
                'url': host + '/logout?callback=' + host + '/home/Oauth/getToken/appid/' + appid + '/state/admin.html',
            }
            return render(request, 'CasLogin/404.html', context)

def casLogout(request):
    host = settings.CAS_HOST
    appid = settings.CAS_APPID
    logout(request)
    return HttpResponseRedirect(host + '/logout?callback=' + host + '/home/Oauth/getToken/appid/' + appid + '/state/admin.html')
    # return HttpResponse("<h1>兑票失败</h1>")

def loginError(request):
    host = settings.CAS_HOST
    appid = settings.CAS_APPID
    context = {
        'error': '非管理员无法登陆',
        'url': host + '/logout?callback=' + host + '/home/Oauth/getToken/appid/' + appid + '/state/admin.html',
    }
    return render(request, 'CasLogin/404.html', context)

def loginSuccess(request):
    return HttpResponse("登录成功，你可以访问已授权的接口，<a href='/caslogin/casLogout'>退出登录</a>")